function app() {
    return {
        // 状态管理
        sidebarOpen: window.innerWidth >= 1024,
        currentPage: 1,

        // 学生数据储存
        students: [],
        all_rank:[],
        all_class:[],
        isLoading: false,
        error: null,

        // 初始化方法
        init() {
            this.handleResize();
            window.addEventListener('resize', this.handleResize.bind(this));
            // 初始化时加载数据
            this.loadStudents(); 
            this.loadRank();
            this.loadClass();
        },

        // 新增数据获取方法
        async loadStudents() {
            this.isLoading = true;
            this.error = null;
            try {
                // http://localhost:8080
                const response = await fetch('/student/list');
                if (!response.ok) throw new Error(`HTTP错误! 状态码: ${response.status}`);
                this.students = await response.json();
            } catch (error) {
                this.error = `数据加载失败: ${error.message}`;
                console.error('API请求错误:', error);
            } finally {
                this.isLoading = false;
            }
        },

        async loadRank() {
            try {
                const response = await fetch('/student/rank');
                if (!response.ok) throw new Error(`HTTP错误! 状态码: ${response.status}`);
                const data = await response.json();
                // 提取 rank 字段并转换为字符串数组
                this.all_rank = data.map(item => String(item.rank)); 
            } catch (error) {
                console.error('年级加载失败:', error);
                this.all_rank = [];
            }
        },

        async loadClass() {
            try {
                const response = await fetch('/student/class');
                if (!response.ok) throw new Error(`HTTP错误! 状态码: ${response.status}`);
                const data = await response.json();
                // 提取 class 字段并转换为字符串数组
                this.all_class = data.map(item => String(item.class)); 
            } catch (error) {
                console.error('班级加载失败:', error);
                this.all_class = [];
            }
        },
        
        // 导航配置
        navItems: [
            { id: 1, title: '首页' },
            { id: 2, title: '批量添加' },
            { id: 3, title: '关于项目' }
        ],

        // 原有状态
        showEditModal: false,
        showDeleteModal: false,
        editingStudent: null,
        deletingStudent: null,

        // 新增方法
        startEdit(student) {
            this.editingStudent = {...student}; // 浅拷贝学生对象
            this.showEditModal = true;
        },

        async updateStudent() {
            try {
                // 转换字段类型
                const payload = {
                    ...this.editingStudent,
                    rank: Number(this.editingStudent.rank),
                    class: Number(this.editingStudent.class),
                    dormitory: Number(this.editingStudent.dormitory),
                    dormitory_room: Number(this.editingStudent.dormitory_room),
                    credits: Number(this.editingStudent.credits),
                    id: Number(this.editingStudent.id)
                };
        
                const response = await fetch(`/student/update`, {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(payload)
                });
        
                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.message || '更新失败');
                }
        
                await this.loadStudents();
                this.showEditModal = false;
                this.successMessage = '更新成功！';
                setTimeout(() => this.successMessage = null, 3000);
            } catch (error) {
                this.error = `更新失败: ${error.message}`;
                console.error('更新错误:', error);
                setTimeout(() => this.error = null, 5000);
            }
        },

        startDelete(student) {
            this.deletingStudent = student;
            this.showDeleteModal = true;
        },

        async confirmDelete() {
            try {
                const response = await fetch(`/student/delete?id=${this.deletingStudent.id}`, {
                    method: 'GET'
                });
                
                if (!response.ok) throw new Error('删除失败');
                await this.loadStudents(); // 刷新数据
                this.showDeleteModal = false;
            } catch (error) {
                this.error = `删除失败: ${error.message}`;
                console.error('删除错误:', error);
            }
        },

        // 页面内容
        pages: [
            {
                id: 1,
                title: '',
                content: `
                    <div class="flex flex-col gap-4">
                        <div class="overflow-x-auto rounded-box border border-base-content/5 bg-base-100 p-4 flex justify-between">
                            <input x-model="searchQuery" type="text" placeholder="查找学生名字" class="input input-bordered" />
                            <div>
                                <select x-model="selectedGrade" class="select">
                                    <option value="" selected>全部年级</option>
                                    <template x-for="rankVal in all_rank" :key="rankVal">
                                        <option x-text="rankVal + ' 年级'" :value="rankVal"></option>
                                    </template>
                                </select>

                                <select x-model="selectedClass" class="select">
                                    <option value="" selected>全部班级</option>
                                    <template x-for="classVal in all_class" :key="classVal">
                                        <option x-text="classVal + ' 班'" :value="classVal"></option>
                                    </template>
                                </select>
                            </div>
                        </div>
                        <!-- 加载状态 -->
                        <template x-if="isLoading">
                            <div class="text-center p-8">
                                <span class="loading loading-infinity loading-lg"></span>
                                <p class="mt-2">正在加载数据...</p>
                            </div>
                        </template>

                        <!-- 错误提示 -->
                        <template x-if="error">
                            <div class="alert alert-error">
                                <svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />
                                </svg>
                                <span x-text="error"></span>
                            </div>
                        </template>
                        <div>
                            <div class="overflow-x-auto rounded-box border border-base-content/5 bg-base-100">
                                <table class="table">
                                    <!-- head -->
                                    <thead>
                                    <tr>
                                        <th></th>
                                        <th>学号</th>
                                        <th>姓名</th>
                                        <th>年级</th>
                                        <th>班级</th>
                                        <th>宿舍楼</th>
                                        <th>房间号</th>
                                        <th>积分</th>
                                    </tr>
                                    </thead>
                                    <tbody>
                                        <template x-for="(student, index) in filteredStudents" :key="student.id">
                                            <tr>
                                                <th x-text="index + 1">1</th>
                                                <td x-text="student.id">1184220836</td>
                                                <td x-text="student.name">沙增超</td>
                                                <td x-text="student.rank">3</td>
                                                <td x-text="student.class">3</td>
                                                <td x-text="student.dormitory">5</td>
                                                <td x-text="student.dormitory_room">214</td>
                                                <td x-text="student.credits">50</td>
                                                <td>
                                                    <input name="point" placeholder="分数" type="number" step="0.5" class="input input-bordered w-20">
                                                    <button class="btn btn-outline btn-success">保存</button>
                                                    <button class="btn btn-outline btn-info" @click="startEdit(student)">修改学生信息</button>
                                                    <button class="btn btn-outline btn-error" @click="startDelete(student)">删除</button>
                                                </td>
                                            </tr>
                                        </template>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>


                    <!-- 弹窗 -->
                    <template x-if="showEditModal">
                        <div class="modal modal-open">
                            <div class="modal-box">
                                <h3 class="font-bold text-lg">修改学生信息</h3>
                                <form @submit.prevent="updateStudent">
                                    <div class="form-control">
                                        <label class="label">
                                            <span class="label-text">学号</span>
                                        </label>
                                        <input type="text" x-model="editingStudent.id" class="input input-bordered" disabled>
                                    </div>
                                    <div class="form-control">
                                        <label class="label">
                                            <span class="label-text">姓名</span>
                                        </label>
                                        <input type="text" x-model="editingStudent.name" class="input input-bordered" required>
                                    </div>
                                    <div class="form-control">
                                        <label class="label">
                                            <span class="label-text">年级</span>
                                        </label>
                                        <input type="text" x-model="editingStudent.rank" class="input input-bordered" required>
                                    </div>
                                    <div class="form-control">
                                        <label class="label">
                                            <span class="label-text">班级</span>
                                        </label>
                                        <input type="text" x-model="editingStudent.class" class="input input-bordered" required>
                                    </div>
                                    <div class="form-control">
                                        <label class="label">
                                            <span class="label-text">宿舍楼</span>
                                        </label>
                                        <input type="text" x-model="editingStudent.dormitory" class="input input-bordered" required>
                                    </div>
                                    <div class="form-control">
                                        <label class="label">
                                            <span class="label-text">房间号</span>
                                        </label>
                                        <input type="text" x-model="editingStudent.dormitory_room" class="input input-bordered" required>
                                    </div>
                                    <div class="form-control">
                                        <label class="label">
                                            <span class="label-text">积分</span>
                                        </label>
                                        <input type="text" x-model="editingStudent.credits" class="input input-bordered" required>
                                    </div>                                   
                                    <div class="modal-action">
                                        <button type="submit" class="btn btn-primary">保存修改</button>
                                        <button type="button" class="btn" @click="showEditModal = false">取消</button>
                                    </div>
                                </form>
                            </div>
                        </div>
                    </template>

                    <template x-if="showDeleteModal">
                        <div class="modal modal-open">
                            <div class="modal-box">
                                <h3 class="font-bold text-lg">确认删除</h3>
                                <p class="py-4">确定要删除学生 <span x-text="deletingStudent.name"></span>（学号：<span x-text="deletingStudent.id"></span>）吗？此操作不可恢复！</p>
                                <div class="modal-action">
                                    <button class="btn btn-error" @click="confirmDelete">确认删除</button>
                                    <button class="btn" @click="showDeleteModal = false">取消</button>
                                </div>
                            </div>
                        </div>
                    </template>
                `
            },

            {
                id: 2,
                title: '批量添加',
                content: `
                        <div x-data="{
                                rawInput: '',
                                message: '',
                                isError: false,
                                isLoading: false,

                                async submit() {
                                    this.isLoading = true;
                                    this.message = '';
                                    
                                    try {
                                        const response = await fetch('/students/batch', {
                                            method: 'POST',
                                            headers: { 'Content-Type': 'text/plain' },
                                            body: this.rawInput
                                        });
                                        
                                        const result = await response.json();
                                        
                                        if (response.ok) {
                                            this.isError = false;
                                            this.rawInput = '';
                                        } else {
                                            this.isError = true;
                                        }
                                        this.message = result.message;
                                        
                                    } catch (error) {
                                        this.isError = true;
                                        this.message = '网络连接失败';
                                    }
                                    this.isLoading = false;
                                }
                            }">
                            <div class="mb-4">
                                    <textarea 
                                        class="textarea textarea-bordered w-full h-48"
                                        placeholder="每行格式：学生号ID,姓名,年级,班级,宿舍楼,房间号,积分&#10;示例：&#10;1184220836,张三,1,3,5,101,85.5&#10;1184220837,李四,2,4,6,203,92.0"
                                        x-model="rawInput"
                                    ></textarea>
                            </div>
                            <button 
                                class="btn btn-primary w-full"
                                :class="{ 'loading': isLoading }"
                                @click="submit"
                                :disabled="isLoading || !rawInput.trim()"
                            >
                                批量提交
                            </button>
                            <div x-show="message" class="mt-4 alert" :class="isError ? 'alert-error' : 'alert-success'">
                                <span x-text="message"></span>
                            </div>
                        </div>
                `
            },

            {
                id: 3,
                title: '关于项目',
                content: `
                    <div class="card bg-base-100 shadow">
                        <div class="card-body">
                            <h3 class="card-title">项目简介</h3>
                            <p>该项目使用了 Actix-Web & SQlite</p>
                        </div>
                    </div>
                `
            },
            // 其他页面内容...
        ],


        // 新增搜索功能相关状态
        searchQuery: '',
        selectedGrade: '',
        selectedClass: '',

        // 计算属性过滤数据
        get filteredStudents() {
            return this.students.filter(student => {
                const matchesSearch = student.name.toLowerCase().includes(this.searchQuery.toLowerCase());
                const matchesGrade = !this.selectedGrade || student.rank == this.selectedGrade;
                const matchesClass = !this.selectedClass || student.class == this.selectedClass;
                return matchesSearch && matchesGrade && matchesClass;
            });
        },

        
        // 方法
        changePage(pageId) {
            this.currentPage = pageId;
            if (window.innerWidth < 1024) {
                this.sidebarOpen = false;
            }
        },

        // 响应式处理
        handleResize() {
            this.sidebarOpen = window.innerWidth >= 1024
        }
    }
}